<?php

namespace app\controller\admin\genshinteam;

use app\model\api\GenshinRelics;
use laytp\controller\Backend;
use laytp\library\CommonFun;
use laytp\library\Tree;

/**
 * 菜单控制器
 */
class Relics extends Backend
{

    public $model;
    protected $noNeedLogin = []; // 无需登录即可请求的方法
    protected $noNeedAuth = ['index', 'info']; // 无需鉴权即可请求的方法

    public function _initialize()
    {
        $this->model = new GenshinRelics();
    }

    /**
     * 圣遗物列表
     * @return false|string|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function relics(){
        $data = (new GenshinRelics())->getAllRelics();
        return $this->success('数据获取成功', $data);
    }

    //添加
    public function add()
    {
        $post = CommonFun::filterPostData($this->request->post());

        $insData['relics_name'] = $post['name'];
        $insData['icon']  = $post['icon'];
        $insData['star']  = $post['star'];
        try {
            $save = $this->model->save($insData);
            if (!$save) throw new \Exception('保存失败');
            $this->clearCache();
            return $this->success('保存成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    //编辑
    public function edit()
    {
        $id = $this->request->param('id');
        $post = CommonFun::filterPostData($this->request->post());
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        $row->relics_name = $post['name'];
        $row->icon  = $post['icon'];
        $row->star  = $post['star'];
        try {
            $save = $row->save();
            if ($save === false) throw new \Exception('保存失败');
            $this->clearCache();
            return $this->success('保存成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    public function info(){
        $id = $this->request->param('id');
        $relics = $this->model->where('id',$id)->find()->toArray();
        $relics['relics_name']   = !empty($relics['relics_name'])?$relics['relics_name']:'';
        $relics['icon']   = !empty($relics['icon'])?$relics['icon']:'';
        $relics['star']   = !empty($relics['star'])?$relics['star']:'';
        return $this->success('获取成功', $relics);
    }
}
